import pymysql
import numpy as np
import cv2

def connect_database():
    """连接数据库并返回连接对象。"""
    return pymysql.connect(
        host='39.106.77.250',
        user='root',
        password='scce_202',
        database='map_db',
        charset='utf8mb4'
    )

def fetch_map_data():
    """从数据库读取节点和边数据，构建地图数据结构。"""
    db = connect_database()
    try:
        with db.cursor() as cursor:
            # 读取节点数据
            cursor.execute("SELECT id, x, y, name FROM nodes WHERE is_deleted = 0")
            nodes = cursor.fetchall()
            # 读取边数据
            cursor.execute("SELECT source_node, target_node FROM edges WHERE is_deleted = 0")
            edges = cursor.fetchall()
    finally:
        db.close()

    # 将节点和边转换为字典结构
    node_dict = {node[0]: (node[1], node[2]) for node in nodes}
    edge_list = [(node_dict[edge[0]], node_dict[edge[1]]) for edge in edges]

    return node_dict, edge_list

def create_pgm_from_map_data(width, height, resolution=1):
    """生成PGM文件格式的地图图像并保存。"""
    node_dict, edge_list = fetch_map_data()

    # 初始化白色图像
    map_img = np.ones((height, width), dtype=np.uint8) * 255
    
    # 绘制小矩形内部和边缘
    for node_id, (x, y) in node_dict.items():
        # 定义小矩形的大小
        rect_size = 10  # 可根据需要调整
        top_left = (int(x * resolution - rect_size / 2), int(y * resolution - rect_size / 2))
        bottom_right = (int(x * resolution + rect_size / 2), int(y * resolution + rect_size / 2))
        
        # 在图像中绘制填充的小矩形（黑色）
        cv2.rectangle(map_img, top_left, bottom_right, color=0, thickness=-1)

    # 绘制边
    for (x1, y1), (x2, y2) in edge_list:
        pt1 = (int(x1 * resolution), int(y1 * resolution))
        pt2 = (int(x2 * resolution), int(y2 * resolution))
        cv2.line(map_img, pt1, pt2, 0, 1)

    # 保存为PGM文件
    cv2.imwrite('map.pgm', map_img)
    print("地图已保存为 map.pgm")

def load_map_from_pgm(pgm_path):
    """从PGM文件加载地图数据，返回numpy数组。"""
    return cv2.imread(pgm_path, cv2.IMREAD_GRAYSCALE)

def path_planning(start, goal, map_source="database", pgm_path="map.pgm"):
    """
    路径规划函数。默认从数据库读取地图，但可以从PGM文件读取。
    start, goal: 起始点和目标点坐标
    map_source: 指定地图来源 ("database" 或 "pgm")
    """
    if map_source == "database":
        # 从数据库构建地图
        _, edge_list = fetch_map_data()
        map_data = edge_list
    elif map_source == "pgm":
        # 从PGM文件加载地图
        map_data = load_map_from_pgm(pgm_path)
    else:
        raise ValueError("不支持的地图来源类型：请使用 'database' 或 'pgm'")

    # 此处添加路径规划算法的实现，例如A*、Dijkstra等
    # 暂时仅返回起点和终点的简单连线路径（示例）
    print("路径规划尚未实现，起点:", start, "终点:", goal)
    return [start, goal]

    

def test_path_planning():
    # 生成PGM地图
    create_pgm_from_map_data(1000, 1000)

    # 定义起点和终点
    start = (100, 200)  # 你可以根据节点的坐标设置这些值
    goal = (300, 400)

    # 测试从数据库读取地图
    print("从数据库进行路径规划...")
    path_from_db = path_planning(start, goal, map_source="database")
    print("路径（从数据库）：", path_from_db)

    # 测试从PGM文件读取地图
    print("从PGM文件进行路径规划...")
    path_from_pgm = path_planning(start, goal, map_source="pgm", pgm_path="map.pgm")
    print("路径（从PGM文件）：", path_from_pgm)

if __name__ == "__main__":
    test_path_planning()
